package com.shop.loan.qiniu;

import cn.hutool.core.io.FileUtil;
import cn.hutool.crypto.digest.MD5;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import xyz.erupt.core.exception.EruptWebApiRuntimeException;
import xyz.erupt.core.util.MimeUtil;

import java.io.InputStream;
import java.util.UUID;


@Slf4j
@Component
public class QiNiuUtil {

//    public static String ak = "IEw6joBbAWZa7jqad8X6gAvM9SklUK3ujxBbmxTO";
//
//    public static String sk = "C6ocVftPi4v1TxlWgCJdLPYvOAnHro4Oh-J9Nbik";
//
//    public static String bucket = "rental-kuai";
//
//    public static String fileDomainByQn = "https://qnfile.zujikj.com";


    @Value("${api.qiniu.ak}")
    private String ak;

    @Value("${api.qiniu.sk}")
    private String sk;

    @Value("${api.qiniu.bucket}")
    private String bucket;

    @Value("${api.qiniu.fileDomainByQn}")
    private String fileDomainByQn;


    public String getFileDomainByQn() {
        return fileDomainByQn;
    }

    public void setFileDomainByQn(String fileDomainByQn) {
        this.fileDomainByQn = fileDomainByQn;
    }

    /**
     * 生成上传token
     *
     * @return
     */
    public String getUpToken(String key) {
        Auth auth = Auth.create(ak, sk);
        StringMap putPolicy = new StringMap();
        //默认过期时间 3600秒*2 = 2小时
        long expireSeconds = 3600 * 2;
        String upToken;
        if (StringUtils.isEmpty(key)) {
            upToken = auth.uploadToken(bucket, null, expireSeconds, putPolicy);
        } else {
            //覆盖上传
            upToken = auth.uploadToken(bucket, key, expireSeconds, putPolicy);
        }
        return upToken;
    }

    /**
     * 上传文件（流）
     *
     * @param inputStream
     * @param path
     * @return
     */
    public String upLoad(InputStream inputStream, String path) {
        String fileName = UUID.randomUUID().toString();
        if (path.contains(".")) {
            String[] item = path.split("\\.");
            fileName = fileName + "." + item[item.length - 1];
        }
        //根据存储地区创建上传对象
        UploadManager uploadManager = new UploadManager(new Configuration(Region.huadong()));
        String uploadToken = getUpToken(null);
        try {
            Response response = uploadManager.put(inputStream, fileName, uploadToken, null, MimeUtil.getMimeType(path));
            if (!response.isOK()) {
                throw new EruptWebApiRuntimeException("上传七牛云存储空间失败");
            }
            return "/" + fileName;
        } catch (QiniuException ex) {
            throw new EruptWebApiRuntimeException(ex.response.toString());
        }
    }

    /**
     * 上传文件（本地文件）
     *
     * @param filePath
     * @param key
     * @return
     */
    public String upLoadByFilePath(String filePath, String key) {
        //根据存储地区创建上传对象
        UploadManager uploadManager = new UploadManager(new Configuration(Region.huadong()));
        String uploadToken = Auth.create(ak, sk).uploadToken(bucket);
        try {
            if (!StringUtils.hasLength(key)) {
                key = MD5.create().digestHex(UUID.randomUUID().toString());
                if (StringUtils.hasLength(FileUtil.getSuffix(filePath))) {
                    key = key + "." + FileUtil.getSuffix(filePath);
                }
            }
            Response response = uploadManager.put(filePath, key, uploadToken);
            if (!response.isOK()) {
                throw new EruptWebApiRuntimeException("上传七牛云存储空间失败");
            }
            return "/" + key;
        } catch (QiniuException ex) {
            ex.printStackTrace();
        }
        return null;
    }


}
